package algorithm.dynamicProgramming.leetcode;
//509. 斐波那契数
public class fib {
    public static void main(String[] args) {
        System.out.println(fib2(1));
//        System.out.println(fib(30));
        System.out.println(fib3(6));
        System.out.println(fib2(6));
    }


    public static int fib(int n) {
        if (n==0){
            return 0;
        }else if (n==1){
            return 1;
        }else {
            return fib(n-2)+fib(n-1);
        }
    }

    public static int fib2(int n){
        int[] f = new int[n+1];
        f[0]=0;
        f[1]=1;
        if(n==0 ||n==1){
            return n;
        }
        for (int i = 2;i<=n;i++){
            //如果传0传1会导致下式下标变为负数
            f[i] = f[i-2]+f[i-1];
        }
        return f[n];
    }

    public static int fib3(int n){
        if (n<2){
            return n;
        }
        int p=0,q=1,res=0;
        for (int i =2;i<=n;i++){
            res=q+p;
            p=q;
            q=res;

        }
        return res;
    }
}
